from crypt import methods

from flask import Blueprint, render_template, flash, redirect, current_app, url_for, request
from flask_wtf import FlaskForm
from wtforms import StringField, SubmitField, PasswordField
from wtforms.validators import DataRequired
from ..models.models import Dbconn
from flask_login import login_user, login_required, logout_user, current_user
from app import LoginUser


bp = Blueprint('main', __name__)

class LoginForm(FlaskForm):
    name = StringField('账号', validators=[DataRequired()])
    passwd = StringField('密码', validators=[DataRequired()])
    submit = SubmitField('提交')

@bp.route('/', methods=['GET', 'POST'])
def login():
    dbs = Dbconn()
    login_form = LoginForm()
    if login_form.validate_on_submit():
        result = dbs.verify_password(login_form.name.data, login_form.passwd.data)
        if result:
            luser = LoginUser(result)
            login_user(luser)
            return redirect (request.args.get('next') or ('/main'))
        else:
            flash('用户名戓密码不正确')
    return render_template('login.html', form=login_form)

@bp.route('/main', methods=['GET', 'POST'])
@login_required
def main():
    content = [['采购', '10', '￥19000'], ['销售', '5', '9500'], ['库存', '5', '0']]
    return render_template('main.html', items=content)

@bp.route('/logout', methods=['GET', 'POST'])
@login_required
def logout():
    logout_user()
    return redirect('/')

@bp.route('/sell', methods=['GET', 'POST'])
@login_required
def sell():
    return render_template('sell.html')

@bp.route('/stock', methods=['GET', 'POST'])
@login_required
def stock():
    return render_template('stock.html')

@bp.route('/user', methods=['GET', 'POST'])
@login_required
def usermg():
    return render_template('usermg.html')

@bp.route('/customer', methods=['GET', 'POST'])
@login_required
def customer():
    return render_template('customer.html')

@bp.route('/goods', methods=['GET', 'POST'])
@login_required
def goods():
    return render_template('goods.html')

@bp.route('/supplier', methods=['GET', 'POST'])
@login_required
def supplier():
    return render_template('supplier.html')